package org.emergency.framework.serviceImpl.oa;

import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.emergency.framework.bean.PageHelper;
import org.emergency.framework.common.Context;
import org.emergency.framework.common.IdsService;
import org.emergency.framework.common.UserSession;
import org.emergency.framework.constant.IDConstant;
import org.emergency.framework.constant.SessionConstant;
import org.emergency.framework.dao.oa.ITbDepartmentDAO;
import org.emergency.framework.dao.oa.ITbRoleDAO;
import org.emergency.framework.dao.oa.ITbUserDAO;
import org.emergency.framework.model.TbDepartment;
import org.emergency.framework.model.TbDepartmentTbUserId;
import org.emergency.framework.model.TbPermission;
import org.emergency.framework.model.TbRole;
import org.emergency.framework.model.TbUser;
import org.emergency.framework.model.TbUserDepartment;
import org.emergency.framework.model.TbUserRoleEntity;
import org.emergency.framework.service.common.IRolePermissionMapping;
import org.emergency.framework.service.oa.ITbUserService;
import org.emergency.framework.serviceImpl.oa.help.CheckUserServiceImpl;
import org.emergency.framework.serviceImpl.oa.help.GenerateImg;
import org.springframework.stereotype.Repository;

@Repository("tbUserServiceImpl")
public class TbUserServiceImpl implements ITbUserService {

	/**
	 * check密码服务
	 */
	@Resource(name = "checkUserServiceImpl")
	private CheckUserServiceImpl checkUserServiceImpl;

	@Resource(name = "rolePermissionMappingImpl")
	private IRolePermissionMapping iRolePermissionMapping;

	@Resource(name = "idsServiceImpl")
	private IdsService idsService;

	/**
	 * 当前用户的角色
	 */
	@Resource(name = "tbRoleDAO")
	private ITbRoleDAO tbRoleDAO;

	@Resource(name = "tbUserDAO")
	private ITbUserDAO tbUserDAO;

	@Resource(name = "tbDepartmentDAO")
	private ITbDepartmentDAO tbDepartmentDAO;

	@Override
	public boolean checkLogin(TbUser tbUser) {
		// TODO Auto-generated method stub
		/**
		 * 验证密码
		 */
		if (!checkUserServiceImpl.checkUser(tbUser.getTbUserId(), tbUser
				.getPassword())) {// 密码错误
			return false;
		}
		/**
		 * 密码正确后，取出用户放到session
		 */
		UserSession userSession = new UserSession();
		handleUserSession(tbUser, userSession);

		/**
		 * 密码正确后，修改用户的最后登陆时间
		 */
		Date currentTime = new Date();
		TbUser tbCurrentUser = tbUserDAO.loadObjectById(tbUser.getTbUserId());
		tbCurrentUser.setLastLoginTime(currentTime);
		tbUserDAO.update(tbCurrentUser);
		
		return true;
	}

	@Override
	public boolean delete(TbUser entity) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public List<TbUser> findAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public TbUser loadObjectById(Serializable id) {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean save(TbUser entity, String deptId, String roldId) {
		// TODO Auto-generated method stub

		// role的处理
		Set<TbUserRoleEntity> tbUserRoleEntities = new HashSet<TbUserRoleEntity>();
		TbUserRoleEntity tbUserRoleEntity = new TbUserRoleEntity();
		
		tbUserRoleEntity.setTbRole(new TbRole(roldId));
		tbUserRoleEntity.setTbUser(entity);
		tbUserRoleEntity.setTbUserRoleEntityId(idsService
				.findTablePK(IDConstant.TB_USER_ROLE_ENTITY));
		tbUserRoleEntities.add(tbUserRoleEntity);
		entity.setTbUserRoleEntities(tbUserRoleEntities);

		// dept处理
		Set<TbUserDepartment> tbUserDepartments = new HashSet<TbUserDepartment>();
		TbUserDepartment tbUserDepartment = new TbUserDepartment();
		
		tbUserDepartment.setId(new TbDepartmentTbUserId(deptId,entity.getTbUserId()));
		tbUserDepartment.setTbDepartment(new TbDepartment(deptId));
		tbUserDepartment.setTbUser(entity);
		tbUserDepartments.add(tbUserDepartment);
		entity.setTbUserDepartment(tbUserDepartments);

		try {
			entity.setEnabled(true);
			tbUserDAO.save(entity);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

		return false;
	}

	@Override
	public boolean saveOrUpdate(TbUser entity) {
		// TODO Auto-generated method stub

		return true;
	}

	@Override
	public boolean update(TbUser entity) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public ByteArrayInputStream getImage() {
		ByteArrayInputStream input = null;
		try {
			input = (new GenerateImg()).getImage();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return input;

	}

	private void handleUserSession(TbUser tbUser, UserSession userSession) {
		/**
		 * 用户 ip
		 */
		userSession.setIpAddress(Context.getRequest().getRemoteAddr());
		/**
		 * 取用户
		 */
		TbUser currentUser = (TbUser) tbUserDAO.findListByCmd(
				"from TbUser t where t.tbUserId = ?", -1, 1,
				tbUser.getTbUserId()).get(0);
		userSession.setTbUser(currentUser);
		/**
		 * 取用户的角色
		 */
		List<TbRole> tbRoleList = null;
		try {
			tbRoleList = tbRoleDAO
					.findListByCmd(
							"select t.tbRole from TbUserRoleEntity t where t.tbUser.tbUserId = ?",
							-1, 1, tbUser.getTbUserId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		userSession.setTbRoleList(tbRoleList);
		/**
		 * 取权限list
		 */
		List<TbPermission> tbPermissionList = new ArrayList<TbPermission>();
		for (TbRole tbRole : tbRoleList) {
			tbPermissionList.addAll(iRolePermissionMapping
					.queryTbPermissionByRole(tbRole.getTbRoleId()));
		}
		userSession.setTbPermissionList(tbPermissionList);
		/**
		 * 取部门
		 */
		
		//usersession放入session中
		Context.getSession().setAttribute(SessionConstant.UserSession, userSession);
	}

	// @Override
	// public PageUtil queryTbUserByName(PageUtil pageutiUtil, TbUser tbUser) {
	// // TODO Auto-generated method stub
	// String hqlString = "from TbUser t where t.name like '%"
	// + tbUser.getName() + "%' ";
	//
	// return queryByhql(hqlString, pageutiUtil);
	// }

	/**
	 * 
	 * @param hqlString
	 *            hql语句, 查list,和total,
	 * @param pageUtilUser要填充的对象
	 *            ,要已经存在Page和MaxRow
	 * @return
	 */
	private PageHelper queryByhql(String hqlString, PageHelper pageHelp) {

		List<TbUser> tbuserList = tbUserDAO.findListByCmd(hqlString,
				pageHelp.getCurrentPage(), pageHelp.getItemNum(), null);
		pageHelp.setList(tbuserList);// 把list放进去
		hqlString = "select count(*) from TbUser t where t.isEnabled = true  ";
		Long totalPage = (Long) tbUserDAO.queryForCmd(hqlString, null);
		pageHelp.setTotalPage(totalPage); // 把总页数放进去

		return pageHelp;
	}

	@Override
	public PageHelper queryUser(PageHelper pageUtilUser, String roleId,
			TbUser tbUser, String deptId) {
		// stringBuilder拼语句速度比较快
		StringBuilder hqlStringbBuffer = new StringBuilder();
		hqlStringbBuffer
		.append(" from TbUser t left join fetch t.tbUserRoleEntities tbuserRole left join fetch t.tbUserDepartment tud   where t.isEnabled = true ");
		if(tbUser!=null){
			if (!tbUser.getName().isEmpty()) {// 用户名,模糊查询
				hqlStringbBuffer.append(" and  t.name like  '%" + tbUser.getName()
						+ "%' ");
			}
		}
		if(roleId!=null){
			if (!(roleId.isEmpty())) {// 角色id
				hqlStringbBuffer.append(" and tbuserRole.tbRole.tbRoleId = '"
						+ roleId + "' ");
			}
		}
		if(deptId!=null){
			if (!deptId.isEmpty()) {// 部门id
				hqlStringbBuffer.append(" and  tud.tbDepartment.tbDepartmentId = '" + deptId
						+ "' ");
			}
			
		}
		String hqlString = hqlStringbBuffer.toString();
		return queryByhql(hqlString, pageUtilUser);
	}

	@Override
	public boolean deleteUserById(TbUser tbUser) {
		// TODO Auto-generated method stub

		String hqlString = "update TbUser t set t.isEnabled = false where t.tbUserId = '"
				+ tbUser.getTbUserId() + "' ";
		try {
			tbUserDAO.executeDelOrUpdateHql(hqlString);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;

	}

	@Override
	public TbUser queryUserById(TbUser tbUser) {
		// TODO Auto-generated method stub

		return tbUserDAO.loadObjectById(tbUser.getTbUserId());

	}

	@Override
	public boolean save(TbUser entity) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean editCurrentUser(TbUser entity){
		TbUser tbCurrentUser = 	tbUserDAO.loadObjectById(entity.getTbUserId());
		tbCurrentUser.setName(entity.getName());
		tbCurrentUser.setPassword(entity.getPassword());
		try {
			tbUserDAO.saveOrUpdate(tbCurrentUser);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	@Override
	public boolean editUser(TbUser entity, String deptId, String roldId) {
		// TODO Auto-generated method stub

		String hqlroleDeleteString = "delete from TbUserRoleEntity t where t.tbUser.tbUserId= '"
				+ entity.getTbUserId() + "' ";
		String hqluserDeptString = "delete from TbUserDepartment t where t.tbUser.tbUserId ='"
			+entity.getTbUserId()+"'";
		
		// 执行删除操作
		
		// role的处理
		TbRole tbRole = new TbRole(roldId);
		Set<TbUserRoleEntity> tbUserRoleEntities = new HashSet<TbUserRoleEntity>();
		TbUserRoleEntity tbUserRoleEntity = new TbUserRoleEntity();
		tbUserRoleEntity.setTbRole(new TbRole(roldId));
		tbUserRoleEntity.setTbUser(entity);
		tbUserRoleEntity.setTbUserRoleEntityId(idsService
				.findTablePK(IDConstant.TB_USER_ROLE_ENTITY));
		tbUserRoleEntities.add(tbUserRoleEntity);
		entity.setTbUserRoleEntities(tbUserRoleEntities);

		// dept处理
		Set<TbUserDepartment> tbUserDepartments = new HashSet<TbUserDepartment>();
		TbUserDepartment tbUserDepartment = new TbUserDepartment();
		
		tbUserDepartment.setId(new TbDepartmentTbUserId(deptId,entity.getTbUserId()));
		tbUserDepartment.setTbDepartment(new TbDepartment(deptId));
		tbUserDepartment.setTbUser(entity);
		tbUserDepartments.add(tbUserDepartment);
		entity.setTbUserDepartment(tbUserDepartments);
		
		try {
			entity.setEnabled(true);
			tbUserDAO.executeDelOrUpdateHql(hqlroleDeleteString);
			tbUserDAO.executeDelOrUpdateHql(hqluserDeptString);
			tbUserDAO.saveOrUpdate(entity);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

		return false;
	}

}
